﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace d39
{
    public static class Util
    {
        public static int Max<T>(this IEnumerable<T> sequence, Func<T, int> selector, int defaultValue)
        {
            return sequence.Any() ? sequence.Max(selector) : defaultValue;
        }
        private static DateTime? lastModifiedDateUtc;
        public static DateTime LastModifiedDateUtc
        {
            get
            {
                if (lastModifiedDateUtc == null)
                {
                    lastModifiedDateUtc = File.GetLastWriteTimeUtc(Path.Combine(HttpContext.Current.Server.MapPath("~/"), "bin", "d39.dll"));
                }
                return (DateTime)lastModifiedDateUtc;
            }
        }
        public static void SetCachingHeaders(this HttpResponse response)
        {
            response.Cache.SetExpires(DateTime.Now + TimeSpan.FromDays(365));
            response.Cache.SetLastModified(LastModifiedDateUtc);
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetETag(HttpContext.Current.Request.RawUrl.GetHashCode() + "/" + LastModifiedDateUtc.GetHashCode());
        }

        public static LayerSet Union(this IEnumerable<LayerSet> layerSets)
        {
            var result = LayerSet.Empty;
            foreach (var layerSet in layerSets) result |= layerSet;
            return result;
        }

        public static IEnumerable<T> Pattern<T>(int count, params T[] pattern)
        {
            return Pattern(count, (IEnumerable<T>)pattern);
        }
        public static IEnumerable<T> Pattern<T>(int count, IEnumerable<T> pattern)
        {
            int i = 0;
            while (i < count)
            {
                foreach (var item in pattern)
                {
                    yield return item;
                    i++;
                    if (i >= count) yield break;
                }
            }
        }
    }
}